package server.email;

import static server.email.EncodingUtils.decodePath;
import static server.email.EncodingUtils.encodePath;

import java.net.URLEncoder;
import java.util.Map;

import javax.mail.NoSuchProviderException;
import javax.mail.internet.AddressException;

import client.bean.Member;
import client.bean.Plan;

public class EmailHelper {
	private static final String UNIQUE_URL_SEPARATOR = ";;";

	public static void spreadMeetingInformation(Plan plan) throws AddressException, NoSuchProviderException {
		for (Map.Entry<Member, Boolean> entry : plan.getMembers().entrySet()) {
			Boolean alreadyAccepted = entry.getValue();
			if (!alreadyAccepted) {
				Member member = entry.getKey();
				String emailText = getEmailText(plan, member);
				String subject = getEmailSubject(plan);
				SendMail mail = new SendMail(member.getEmail(), subject, emailText);
				mail.send();
			}
		}
	}

	private static String getEmailSubject(Plan plan) {
		return "TimeBooking: " + plan.getName();
	}

	private static String getEmailText(Plan plan, Member member) {
		StringBuilder emailText = new StringBuilder();
		emailText.append("<h3>Hello dear " + member.getName() + "!").append("</h3>");
		emailText.append("Your email has been added to members of <strong>" + plan.getName() + "</strong> meeting.").append("<br>");
		emailText.append("(" + plan.getDescription()).append(")<br>");
		emailText.append("To approve your participation please click to the following link:<strong>");
		emailText.append(getPlanLink(plan, member)).append("</strong><br>");
		emailText.append("<br>");
		emailText.append("<strong>If you're not interested in this event please ignore this email.</strong>");
		return emailText.toString();
	}

	private static String getPlanLink(Plan plan, Member member) {
		StringBuilder planLink = new StringBuilder();
		planLink.append("<a href=\"");
		planLink.append("http://localhost:8080/plan.html?id=");
		planLink.append(getUniqueURL(plan.getId(), member.getEmail()) + "\"");
		planLink.append(" target=\"_blank\">");
		planLink.append("CLICK");
		planLink.append("</a>");
		return planLink.toString();
	}

	public static String getUniqueURL(long planId, String email) {
		String encodePath = encodePath(email + UNIQUE_URL_SEPARATOR + planId);
		return URLEncoder.encode(encodePath);
	}

	public static PathKey getURLFromUniquePath(String encodedPath) {
		String path = decodePath(encodedPath);
		String[] pathElements = path.split(UNIQUE_URL_SEPARATOR);
		String email = pathElements[0];
		Long planId = new Long(pathElements[1]);
		return new PathKey(planId, email);
	}

	public static class PathKey {
		private long planId;
		private String email;

		public PathKey(long planId, String email) {
			this.planId = planId;
			this.email = email;
		}

		public long getPlanId() {
			return planId;
		}

		public String getEmail() {
			return email;
		}
	}
}
